package com.monitor.service.parser.impl;

import com.monitor.model.ServerStatus;
import com.monitor.service.parser.MetricParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 应用状态指标解析器
 * 负责解析curl命令返回的HTTP状态码，判断应用是否启动成功
 */
public class AppStatusMetricParser implements MetricParser {
    private static final Logger logger = LoggerFactory.getLogger(AppStatusMetricParser.class);

    @Override
    public void parse(String commandOutput, ServerStatus status) {
        try {
            // commandOutput格式类似：HTTP/1.1 200 OK 或 Connection refused
            String result = commandOutput.trim();
            boolean isRunning = false;
            String statusMessage = "应用未启动";
            
            // 判断HTTP状态码
            if (result.contains("200 OK")) {
                isRunning = true;
                statusMessage = "运行正常";
            } else if (result.contains("Connection refused")) {
                statusMessage = "连接被拒绝";
            } else if (result.contains("404")) {
                isRunning = true; // 应用已启动但路径不存在
                statusMessage = "应用已启动，但URL路径不存在";
            } else if (result.contains("500")) {
                isRunning = true; // 应用已启动但内部错误
                statusMessage = "应用已启动，但内部错误";
            } else if (result.contains("302") || result.contains("301")) {
                isRunning = true; // 应用已启动但重定向
                statusMessage = "应用已启动，重定向到其他URL";
            } else if (result.contains("Connection timed out")) {
                statusMessage = "连接超时";
            }
            
            // 设置应用状态
            status.setAppStatus(statusMessage);
            status.setAppRunning(isRunning);
        } catch (Exception e) {
            logger.error("解析应用状态失败: {}", e.getMessage());
            status.setAppStatus("解析错误");
            status.setAppRunning(false);
        }
    }
} 